//index.js
//获取应用实例
const app = getApp()
var QR = require("../../utils/qrcode.js");
var util = require('../../utils/util.js'); 
const hours = []
const mins = []
const times = []

for (let i = 0; i < 25; i++) {
  hours.push(i)
}

for (let i = 1; i < 60; i++) {
  mins.push(i)
}

for (let i = 0; i <= 99; i++) {
  times.push(i)
}
Page({
  data: {
    hours: hours,
    mins: mins,
    times: times,
    hour: 0,
    min: 1,
    time: 0,
    effectiveness: ''
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    
  },
  getUserInfo: function(e) {
    
  },
  changeToSetting: function () {
    wx.navigateTo({
      url: '../setting/setting',
    })
  },
  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 375 / 343;//不同屏幕下canvas的适配比例；设计稿是750宽
      var width = 220;
      var height = 220;//canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  createQrCode: function (url, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    QR.qrApi.draw(url, canvasId, cavW, cavH);
    var that = this;
    //二维码生成之后调用canvasToTempImage();延迟3s，否则获取图片路径为空
    var st = setTimeout(function () {
      that.canvasToTempImage();
      clearTimeout(st);
    }, 3000);

  },
  //获取临时缓存照片路径，存入data中
  canvasToTempImage: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        that.setData({
          imagePath: tempFilePath,
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //点击图片进行预览，长按保存分享图片
  previewImg: function (e) {
    var img = this.data.imagePath
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  },
  bindChange: function (e) {
    const val = e.detail.value
    this.setData({
      hour: this.data.hours[val[0]],
      min: this.data.mins[val[1]],
      time: this.data.times[val[2]]
    })
  },
  formSubmit: function (e) {
    var that = this;
    var url = e.detail.value.url;
    url = "http://www.baidu.com";
    var now = util.formatTime(new Date());
    var times = new Date();
    var time = this.data.time == 0 ? '不限' : this.data.time;
    that.setData({
      effectiveness: "有效性：" + now + ' /' + time + "次"
    });
    wx.setScreenBrightness({
      value: 1
    });
    wx.showToast({
      title: '生成中...',
      icon: 'loading',
      duration: 2000
    });
    var st = setTimeout(function () {
      wx.hideToast()
      var size = that.setCanvasSize();
      //绘制二维码
      that.createQrCode(url, "mycanvas", size.w, size.h);
      that.setData({
        maskHidden: true
      });
      clearTimeout(st);
    }, 2000)
  }
})
